package com.demo.persistencia.generica.dao.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.compass.core.CompassCallback;
import org.compass.core.CompassDetachedHits;
import org.compass.core.CompassException;
import org.compass.core.CompassHits;
import org.compass.core.CompassQuery;
import org.compass.core.CompassSession;
import org.compass.spring.CompassDaoSupport;

import com.demo.persistencia.generica.dao.CompassDao;


/**
 * Clase destinada a realizar busquedas en los indices lucene.
 */
public class CompassDaoImpl<K, T extends Serializable> extends CompassDaoSupport implements CompassDao<K, T> {
	
    private static Logger log= Logger.getLogger(CompassDaoImpl.class);
    
    public List<K> buscarPaginado(String queryIndice, int sizeParametro) {
    	
        CompassDetachedHits results = null;
        final String query = queryIndice;
        final int from = 0;
        final int size = sizeParametro;
        List<K> lstobjetos = new ArrayList<K>();


        results = getCompassTemplate().execute(new CompassCallback<CompassDetachedHits>() {
            public CompassDetachedHits doInCompass(final CompassSession session) {
                CompassQuery compassQuery = session.queryBuilder().queryString(query).useOrDefaultOperator().toQuery();
                CompassHits activeHits = compassQuery.hits();
                CompassDetachedHits detachedHits = null;
                
                if (activeHits.getLength() > (from + size)) {
                    detachedHits = activeHits.detach(from, size);
                } else if (activeHits.getLength() > from) {
                    detachedHits = activeHits.detach(from, (activeHits.getLength() - from));
                }
                return detachedHits;
            }
        });

   
        if (results != null) {
            for (int i = 0; i < results.getHits().length; i++) {
            	lstobjetos.add((K) results.getHits()[i].getData());
            }
        }

        return lstobjetos;
    }
    
    
    public void guardar(final K objeto) {
        super.getCompassTemplate().execute((CompassCallback<K>) new CompassCallback<K>() {

            public K doInCompass(CompassSession session) throws CompassException {
                session.save(objeto);
                log.info("Guardando Objeto : " + objeto.toString());
                return null;
            }
        });
    }
    
    
}
